package com.itheima.health.controller.mobile;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.dto.SmsLoginParam;
import com.itheima.health.result.Result;
import com.itheima.health.service.MobileLoginService;
import com.itheima.health.util.AliyunSmsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/mobile")
@Slf4j
public class ValidateCodeController {
    @Autowired
    private MobileLoginService mobileLoginService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @return
     */
    @PostMapping("/validateCode/send")
    public Result send(@RequestParam String telephone ,String type) throws ClientException {
        log.info("手机号：{}，type,{}", telephone, type);
        AliyunSmsUtils.setNewcode();
        String code = Integer.toString(AliyunSmsUtils.getNewcode());

        log.info("验证码：{}", code);
        //jedis.expire("phone", 300);
        try {
            //AliyunSmsUtils.sendShortMessage(AliyunSmsUtils.VALIDATE_CODE,telephone,code);
        } catch (Exception e) {
            return new Result(true, MessageConst.SEND_VALIDATECODE_FAIL);
        }
        redisTemplate.opsForValue().set("phone", telephone, 3, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set("code", code, 3, TimeUnit.MINUTES);
        return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
    }

    @PostMapping("/login/smsLogin")
    public Result login(@RequestBody SmsLoginParam smsLoginParam){
        String telephone = smsLoginParam.getTelephone();
        String code = smsLoginParam.getValidateCode();
        String rtelephone =(String) redisTemplate.opsForValue().get("phone");
        String rcode =(String) redisTemplate.opsForValue().get("code");
        if(telephone.equals(rtelephone) && code.equals(rcode)){
            return new Result(true,MessageConst.LOGIN_SUCCESS);
        }else {
            return new Result(false,MessageConst.LOGIN_FAIL);
        }
    }
}
